<template>
  <el-dialog
    :title="addForm.id ? '编辑' : '添加'"
    :visible="addDialogVisible"
    width="50%"
    @close="handleDialogClose"
  >
    <el-form
      ref="addFormRef"
      label-width="120px"
      :model="addForm"
      :rules="addFormRules"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="addForm.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="addForm.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="addForm.manager"
          style="width: 80%"
          placeholder="请选择"
        >
          <el-option
            v-for="employee in employees"
            :key="employee.id"
            :label="employee.username"
            :value="employee.username"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="addForm.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click.native="$emit('update:add-dialog-visible', false)"
        >取 消</el-button
      >
      <el-button type="primary" @click="submitAddForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getEmployeeSimpleApi } from '@/api/employees'
import { addDepartmentApi, getDepartDetailApi, updateDepartments } from '@/api/departments'
export default {
  props: {
    // 控制添加子部门对话框显示与隐藏
    addDialogVisible: {
      type: Boolean,
      default: false
    },
    // 操作的部门数据
    currentData: {
      type: Object,
      default: () => ({})
    },
    // 平铺的部门数据
    flatDepartmentData: {
      type: Array,
      default: () => []
    }
  },
  data () {
    const validateCode = (rule, value, callback) => {
      let flag = null
      if (this.addForm.id) {
        flag = this.flatDepartmentData.some(item => item.code === value && item.code !== this.currentData.code)
      } else {
        flag = this.flatDepartmentData.some(item => item.code === value)
      }
      if (flag) {
        callback(new Error('code重复'))
      }
      callback()
    }

    return {
      // 添加子部门表单数据
      addForm: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      // 添加子部门表单校验规则
      addFormRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 2, max: 50, message: '部门名称要求2-50个字符', trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change'] }
        ]
      },
      // select中的员工数据
      employees: []
    }
  },
  mounted () {
    this.getEmployeeSimple()
  },
  methods: {
    // 监听对话框关闭事件
    handleDialogClose () {
      this.$refs.addFormRef.resetFields()
      this.addForm = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      this.$emit('update:add-dialog-visible', false)
    },
    // 获取员工简单数据
    async getEmployeeSimple () {
      const data = await getEmployeeSimpleApi()
      // console.log(data)
      this.employees = data
    },
    // 提交添加子部门表单
    async submitAddForm () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.message.error('表单填写有误')
        if (this.addForm.id) {
          // 代表是编辑
          // console.log(this.addForm.id)
          await updateDepartments(this.addForm)
        } else {
          // 代表是添加
          await addDepartmentApi(this.addForm, this.currentData.id || '')
        }
        // }) bug!!~~!!~~ : })包裹位置错误,会导致无法更新部门但可以添加部门
        // 通知父组件更新组织架构
        this.$emit('update:add-dialog-visible', false)
        this.$message.success('操作成功')
        this.$emit('update-departments')
      })
    },
    // 获取部门详情
    async getDepartDetail (id) {
      const detail = await getDepartDetailApi(id)
      // console.log(detail)
      this.addForm = detail
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
